package com.caiheng.api.service.event.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.caiheng.api.dao.estate.EstateBuildFloorMapper;
import com.caiheng.api.dao.estate.EstateBuildMapper;
import com.caiheng.api.dao.event.*;
import com.caiheng.api.dao.sys.SysUserMapper;
import com.caiheng.api.entity.estate.Estate;
import com.caiheng.api.entity.estate.EstateBuild;
import com.caiheng.api.entity.estate.EstateBuildFloor;
import com.caiheng.api.entity.event.*;
import com.caiheng.api.entity.sys.SysUser;
import com.caiheng.api.service.base.impl.BaseServiceImpl;
import com.caiheng.api.service.estate.EstateService;
import com.caiheng.api.service.event.EventPlanTaskService;
import com.caiheng.api.service.event.EventTerminalGroupService;
import com.caiheng.api.util.GetDistance;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 计划任务：人员计划记录Service业务层处理
 *
 * @author ruoyi
 * @date 2023-12-25
 */
@Service
public class EventPlanTaskServiceImpl extends BaseServiceImpl<EventPlanTaskMapper, EventPlanTask> implements EventPlanTaskService {

    @Resource
    private EventPlanMapper eventPlanMapper;
    @Resource
    private EventPlanTaskMapper eventPlanTaskMapper;
    @Resource
    private EventPlanTaskInfoMapper eventPlanTaskInfoMapper;
    @Resource
    private EventTerminalGroupService eventTerminalGroupService;
    @Resource
    private EstateService estateService;
    @Resource
    private EventTerminalsMapper eventTerminalsMapper;
    @Resource
    private EventPlanTaskLeaderMapper planTaskLeaderMapper;
    @Resource
    private EventPatrolLineMapper patrolLineMapper;
    @Resource
    private EventPatrolLineInfoMapper patrolLineInfoMapper;
    @Resource
    private EventPatrolPointMapper patrolPointMapper;
    @Resource
    private EventCleanAreaMapper cleanAreaMapper;
    @Resource
    private EventCleanAreaListMapper cleanAreaListMapper;
    @Resource
    private EventCleanAreaListInfoMapper cleanAreaListInfoMapper;
    @Resource
    private EventPlanWorkMapper planWorkMapper;
    @Resource
    private EstateBuildFloorMapper buildFloorMapper;
    @Resource
    private EstateBuildMapper buildMapper;
    @Resource
    private SysUserMapper sysUserMapper;

    @Override
    public List<EventPlanTask> selectTaskList(Map<String, Object> map, Integer offset, Integer pageSize) {
        List<EventPlanTask> list = eventPlanTaskMapper.selectTaskList(map, offset, pageSize);
        for (EventPlanTask task : list){
//            task = getTaskDetailByModel(task, null,0, 0);

            Estate estate = estateService.findById(task.getEstateId());
            if(estate != null){
                task.setEstateName(estate.getEstateName());
            }

            if(task.getEventType() == 1 || task.getEventType() == 6) {//巡检
                EventTerminalGroup group = eventTerminalGroupService.findById(task.getEventTargetId());
                if (group != null) {
                    task.setTerminalGroup(group);
                }
            } else if(task.getEventType() == 2) {//巡更
                //路线
                EventPatrolLine patrolLine = patrolLineMapper.selectById(task.getEventTargetId());
                if(patrolLine != null){
                    task.setPatrolLine(patrolLine);
                }
            }else if(task.getEventType() == 3 || task.getEventType() ==  4 || task.getEventType() == 5) {//保洁
                //扫码签到
                EventCleanAreaList area = cleanAreaListMapper.selectById(task.getEventTargetId());
                if(area != null){
                    task.setCleanAreaList(area);
                }
            }

        }
        return list;
    }


    @Override
    public List<EventPlanTask> selectTaskListByQrCode(Map<String, Object> map, Integer offset, Integer pageSize) {
        List<EventPlanTask> list = eventPlanTaskMapper.selectTaskListByQrCode(map, offset, pageSize);
        for (EventPlanTask task : list){
//            task = getTaskDetailByModel(task, null,0, 0);

            Estate estate = estateService.findById(task.getEstateId());
            if(estate != null){
                task.setEstateName(estate.getEstateName());
            }

            if(task.getEventType() == 1 || task.getEventType() == 6) {//巡检
                EventTerminalGroup group = eventTerminalGroupService.findById(task.getEventTargetId());
                if (group != null) {
                    task.setTerminalGroup(group);
                }
            } else if(task.getEventType() == 2) {//巡更
                //路线
                EventPatrolLine patrolLine = patrolLineMapper.selectById(task.getEventTargetId());
                if(patrolLine != null){
                    task.setPatrolLine(patrolLine);
                }
            }else if(task.getEventType() == 3 || task.getEventType() ==  4 || task.getEventType() == 5) {//保洁
                //扫码签到
                EventCleanAreaList area = cleanAreaListMapper.selectById(task.getEventTargetId());
                if(area != null){
                    task.setCleanAreaList(area);
                }
            }

        }
        return list;
    }


    @Override
    public EventPlanTask getTaskDetail(Integer taskId, SysUser sysUser,double lng, double lat) {
        EventPlanTask task = eventPlanTaskMapper.getTaskDetail(taskId);
        if(task != null){
            task = getTaskDetailByModel(task, sysUser, lng, lat);
        }
        return task;
    }

    @Override
    public EventPlanTask getTaskDetailByModel(EventPlanTask task, SysUser sysUser, double lng, double lat) {
        try{
            if(task != null){
                Estate estate = estateService.findById(task.getEstateId());
                if(estate != null){
                    task.setEstateName(estate.getEstateName());
                }

                String workerNames = "";

                QueryWrapper<EventPlanTask> qwTask = new QueryWrapper<>();
                qwTask.eq("work_id", task.getWorkId());
                qwTask.groupBy("worker_sys_user_id");
                List<EventPlanTask> taskList = eventPlanTaskMapper.selectList(qwTask);
                if(CollUtil.isNotEmpty(taskList)){
                    for (EventPlanTask task1 : taskList){
                        SysUser user = sysUserMapper.selectById(task1.getWorkerSysUserId());
                        if(user != null){
                            workerNames += user.getNickName() +",";
                        }
                    }
                }

                if(StrUtil.isNotEmpty(workerNames)){
                    workerNames = workerNames.substring(0, workerNames.length() - 1);
                    task.setWorkerNames(workerNames);
                }

                if(StrUtil.isEmpty(task.getPlanTitle())){
                    EventPlan plan = eventPlanMapper.selectById(task.getEventPlanId());
                    if(plan != null){
                        task.setPlanTitle(plan.getPlanTitle());
                        task.setCheckFinishType(plan.getFinishType());
                    }
                }

                if(task.getFinishType() == null){
                    EventPlanWork work = planWorkMapper.selectById(task.getWorkId());
                    if(work!= null){
                        task.setFinishType(work.getFinishType());
                        task.setWorkState(work.getState());
                    }
                }

                String leaderName = "";

                List<EventPlanTaskLeader> leaders = planTaskLeaderMapper.selectListByColumn("event_plan_id", task.getEventPlanId());
                if(CollUtil.isNotEmpty(leaders)){
                    for (EventPlanTaskLeader leader : leaders){
                        SysUser user = sysUserMapper.selectById(leader.getLeaderSysUserId());
                        if(user != null){
                            leaderName += user.getNickName() +",";
                        }
                    }
                }

                if(StrUtil.isNotEmpty(leaderName)){
                    leaderName = leaderName.substring(0, leaderName.length() - 1);
                    task.setLeaderNames(leaderName);
                }

                // 1-巡检  2-巡更  3-保洁  4-绿化  5-消杀  6-维保
                if(task.getEventType() == 1 || task.getEventType() == 6){//巡检
                    EventTerminalGroup group = eventTerminalGroupService.findById(task.getEventTargetId());
                    if(group != null) {
                        QueryWrapper<EventTerminals> qw = new QueryWrapper<>();
                        qw.eq("group_id", group.getId());
                        qw.eq("state", 1);
                        List<EventTerminals> terminals = eventTerminalsMapper.selectList(qw);
                        if(CollUtil.isNotEmpty(terminals)){
                            for (EventTerminals terminal : terminals){
                                terminal.setEventType(task.getEventType());
                                QueryWrapper<EventPlanTaskInfo> qwInfo = new QueryWrapper<>();
                                qwInfo.eq("event_work_id", task.getWorkId());
                                //完成方式  0 - 任意一人完成  1 - 每人完成一次 2 - 指定人员完成
                                if(task.getFinishType() == 1 || task.getFinishType() == 2){
                                    //需要查询指定人的id
                                    if(sysUser != null){
                                        qwInfo.eq("sys_user_id", sysUser.getUserId());//设备类型的
                                    }
                                }
                                if(task.getEventType() == 6){
                                    qwInfo.eq("target_type", 5);//设备类型的
                                }else{
                                    qwInfo.eq("target_type", 0);//设备类型的
                                }
                                qwInfo.eq("target_id", terminal.getId());//设备id
                                qwInfo.last("limit 1");//设备类型的
                                EventPlanTaskInfo taskInfo = eventPlanTaskInfoMapper.selectOne(qwInfo);
                                if(taskInfo != null){
                                    terminal.setOpState(taskInfo.getState());
                                    terminal.setHandleTime(taskInfo.getHandleTime());
                                    terminal.setSysUserName(taskInfo.getSysUserName());
                                    terminal.setTaskInfo(taskInfo);
                                }

                                if(lng > 0 && lat > 0 && terminal.getLng() != null && terminal.getLat() != null){
                                    double distance = GetDistance.distance(terminal.getLng().doubleValue(),terminal.getLat().doubleValue(), lng,lat);
//                                System.out.println("距离： " + distance + "米");
                                    terminal.setDistance(distance);
                                }
                            }
                        }
                        group.setTerminals(terminals);
                        task.setTerminalGroup(group);
                    }
                } else if(task.getEventType() == 2){//巡更
                    //路线
                    EventPatrolLine patrolLine = patrolLineMapper.selectById(task.getEventTargetId());
                    if(patrolLine != null){
                        QueryWrapper<EventPatrolLineInfo> qwLineInfo = new QueryWrapper<>();
                        qwLineInfo.eq("line_id", patrolLine.getId());
                        qwLineInfo.orderByAsc("sort");
                        List<EventPatrolLineInfo> lineInfosNew = new ArrayList<>();
                        List<EventPatrolLineInfo> lineInfos = patrolLineInfoMapper.selectList(qwLineInfo);
                        if(CollUtil.isNotEmpty(lineInfos)){
                            for (EventPatrolLineInfo info : lineInfos){
                                info.setEventType(task.getEventType());
                                EventPatrolPoint point = patrolPointMapper.selectById(info.getPointId());
                                if(point != null){
                                    QueryWrapper<EventPlanTaskInfo> qwInfo = new QueryWrapper<>();
                                    qwInfo.eq("event_work_id", task.getWorkId());
                                    //完成方式  0 - 任意一人完成  1 - 每人完成一次 2 - 指定人员完成
                                    if(task.getFinishType() == 1 || task.getFinishType() == 2){
                                        //需要查询指定人的id
                                        if(sysUser != null) {
                                            qwInfo.eq("sys_user_id", sysUser.getUserId());//设备类型的
                                        }
                                    }
                                    //事务目标的类型  0 - 设备  1 - 巡更点  2 - 楼层  需要的往后加
                                    qwInfo.eq("target_type", 1);//1 - 巡更点
                                    qwInfo.eq("target_id", point.getId());//巡更点id
                                    qwInfo.last("limit 1");//设备类型的
                                    EventPlanTaskInfo taskInfo = eventPlanTaskInfoMapper.selectOne(qwInfo);
                                    if(taskInfo != null){
                                        point.setOpState(taskInfo.getState());
                                        point.setHandleTime(taskInfo.getHandleTime());
                                        point.setSysUserName(taskInfo.getSysUserName());
                                        point.setTaskInfo(taskInfo);
                                    }

                                    if(lng > 0 && lat > 0  && point.getLng() != null && point.getLat() != null){
                                        double distance = GetDistance.distance(point.getLng().doubleValue(),point.getLat().doubleValue(), lng,lat);
//                                    System.out.println("距离： " + distance + "米");
                                        point.setDistance(distance);
                                    }

                                    info.setPoint(point);
                                    if(point.getState() == 1){
                                        lineInfosNew.add(info);
                                    }
                                }
                            }
                        }
                        patrolLine.setLineInfos(lineInfosNew);
                        task.setPatrolLine(patrolLine);
                    }
                } else if(task.getEventType() == 3 || task.getEventType() ==  4 || task.getEventType() == 5){//3-保洁  4-绿化  5-消杀
                    //扫码签到
                    EventCleanAreaList areaList = cleanAreaListMapper.selectById(task.getEventTargetId());
                    if(areaList != null){
                        List<EventCleanAreaListInfo> areaInfosNew = new ArrayList<>();
                        List<EventCleanAreaListInfo> areaInfos = cleanAreaListInfoMapper.selectListByColumn("area_list_id", areaList.getId());
                        if(CollUtil.isNotEmpty(areaInfos)){
                            for (EventCleanAreaListInfo areaInfo : areaInfos){
                                areaInfo.setEventType(task.getEventType());
                                EventCleanArea cleanArea = cleanAreaMapper.selectById(areaInfo.getAreaId());
                                if(cleanArea != null){
                                    QueryWrapper<EventPlanTaskInfo> qwInfo = new QueryWrapper<>();
                                    qwInfo.eq("event_work_id", task.getWorkId());
                                    //完成方式  0 - 任意一人完成  1 - 每人完成一次 2 - 指定人员完成
                                    if(task.getFinishType() == 1 || task.getFinishType() == 2){
                                        //需要查询指定人的id
                                        if(sysUser != null) {
                                            qwInfo.eq("sys_user_id", sysUser.getUserId());//设备类型的
                                        }
                                    }
                                    qwInfo.eq("target_type", 2);//2 - 楼层
                                    qwInfo.eq("target_id", cleanArea.getId());//保洁绿化消杀点id
                                    qwInfo.last("limit 1");//设备类型的
                                    EventPlanTaskInfo taskInfo = eventPlanTaskInfoMapper.selectOne(qwInfo);
                                    if(taskInfo != null){
                                        cleanArea.setOpState(taskInfo.getState());
                                        cleanArea.setHandleTime(taskInfo.getHandleTime());
                                        cleanArea.setSysUserName(taskInfo.getSysUserName());
                                        cleanArea.setTaskInfo(taskInfo);
                                    }

                                    cleanArea.setDistance(-1d);
                                    if(lng > 0 && lat > 0 && cleanArea.getLng() != null && cleanArea.getLat() != null ){
                                        double distance = GetDistance.distance(cleanArea.getLng().doubleValue(),cleanArea.getLat().doubleValue(), lng,lat);
//                                            System.out.println("距离： " + distance + "米");
                                        cleanArea.setDistance(distance);
                                    }
                                }
                                areaInfo.setCleanArea(cleanArea);

                                if(cleanArea != null && cleanArea.getState() == 1){
                                    areaInfosNew.add(areaInfo);
                                }
                            }
                        }
                        areaList.setAreaInfos(areaInfosNew);
                        task.setCleanAreaList(areaList);
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return task;
    }

    @Override
    public Integer getTaskCount(Map<String, Object> map) {
        return eventPlanTaskMapper.getTaskCount(map);
    }
}
